package com.hongfeng.support.util;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.util.Assert;
import org.springframework.web.util.WebUtils;

public class WebHelper {
	/**
	 * 	从Session中获得某个对象
	 *
	 *	@param request - 当前请求
	 *	@param name - 参数名
	 *	@return O 可能为null
	 *	@throws IllegalArgumentException 当request为null时抛出
	 */
	@SuppressWarnings("unchecked")
	public static <O> O getSessionAttribute(HttpServletRequest request, String name) {
		Assert.notNull(request, "request not should be null when you get parameter");
		Object object = WebUtils.getSessionAttribute(request, name);
		return (object != null) ? (O) object : null;
	}

	/**
	 * 
	 * 	Set一个对象到Session中 如果value为null, Session不为null,将会删除Session中的attribute。
	 *
	 *	@param request - 当前请求
	 *	@param name - 名称
	 *	@param value - 对象
	 *	@throws IllegalArgumentException 当request为null时抛出
	 */
	public static void setSessionAttribute(HttpServletRequest request, String name, Object value) {
		Assert.notNull(request, "request not should be null when you get parameter");
		WebUtils.setSessionAttribute(request, name, value);
	}

	/**
	 * 	删除Session中某个属性
	 *
	 *	@param request	当前请求
	 *	@param name		属性名称
	 * 	@throws IllegalArgumentException 当request为null时抛出
	 */
	public static void removeSessionAttribute(HttpServletRequest request, String name) {
		Assert.notNull(request, "request not should be null when you get parameter");
		HttpSession session = request.getSession();
		if (session != null) {
			session.removeAttribute(name);
		}
	}

	/**
	 * 	删除Session中的所有属性
	 * 
	 *	@param request	当前请求
	 *	@throws IllegalArgumentException 当request为null时抛出
	 */
	@SuppressWarnings("unchecked")
	public static void removeSessionAllAttribute(HttpServletRequest request) {
		Assert.notNull(request, "request not should be null when you get parameter");
		HttpSession session = request.getSession();
		if (session != null) {
			Enumeration<String> attributeNames = session.getAttributeNames();
			while (attributeNames.hasMoreElements()) {
				String attributeName = attributeNames.nextElement();
				session.removeAttribute(attributeName);
			}
		}
	}
}
